package com.weiiew.common.Translation;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author 魏锴
 * @Date 2024/8/25
 */
public class TransApi {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private static final String APP_ID = "20240825002132178";
    private static final String SECURITY_KEY = "2huOKCT_NcekevVYkqAg";

    private static String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        String result = HttpGet.get(TRANS_API_HOST, params);
        assert result != null;
        int begin = result.indexOf("dst");
        return result.substring(begin + 6, result.length() - 4);
    }

    private static Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", APP_ID);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = APP_ID + query + salt + SECURITY_KEY; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

    public static String translate(String originStr, String from, String to){
        return getTransResult(originStr, from, to);
    }

}